<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Admin\Controller as Controller1;

use App\Models\Admin;

use App\Models\Good;
use App\Models\Order;
use App\Models\Supplier;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class AdminController extends Controller1
{



    //管理员登录
    public function login(Request $request){

        $user = $request->username;

        $password = $request->password;
        $user = Admin::where('username',$user)->first();
        if(!$user)
            return $this->failed('用户名不存在');

        $token = Auth::guard('check')->attempt(['username'=>$request->username,'password'=>$request->password]
        );



        if($token) {

            $user->token = 'bearer '.$token;
            return $this->setStatusCode(200)->success($user);
        }
        return $this->failed('密码错误',200);

    }

    //用户微信
    public function login1(Request $request){

        $code = $request->code;
        $username  = $request->username;
        $password  = $request->password;

        if(!$code)
            return $this->failed("请传code值");

        $wechat = new Wechat1Controller();

        $user = $wechat->userFromCode($code);
        if(isset($user['openid'])){
            $result = DB::table('admin_users')->where('openid',$user['openid'])->first();

            if(!$result){//用户不存在

                if($username && $password){
                    $user1 = Admin::where('username',$user)->first();

                    $token=Auth::guard('check')->attempt(['username'=>$username,'password'=>$password]);


                    $user1->token = 'bearer '.$token;

                    if($token) {

                        $user1->openid = $user['openid'];
                        $user1->save();
                        return $this->setStatusCode(200)->success($user1);
                    }
                }else{

                    return $this->failed('用户未绑定');
                }



            }else{

                $token=Auth::guard('check')->attempt(['username'=>$result['username'],'password'=>encrypt($result['password'])]);


                $result->token = 'bearer '.$token;

                if($token) {
                    return $this->setStatusCode(200)->success($result);
                }

                return $this->failed('登录失败',400);
            }
        }





    }

    //根据 订单id获取详情
    public function getInfoFromId(Request $request){


        $order_id = $request->order_id;

        $order = Order::with(["goods:order_id,goods_name,goods_id,goods_price,num,total_money","user:id,name,nickname,mobile"])
            ->select(['id','user_id','money','check_status','order_note','note_img','order_status','pay_status','type','check_time','created_at'])->find($order_id);



        foreach ($order->goods as $k=>$v){

          $goods =  Good::with(["color:id,color","material:id,material"])
                ->where('id',$v['goods_id'])->select(['id','color_id','material_id','No',])->first();
            $order->goods[$k]->color = $goods->color->color;
            $order->goods[$k]->No = $goods->No;
            if($goods->material){
                $order->goods[$k]->str = $goods->color->color.'-'.$goods->material->material;
            }

        }



        return $this->success($order);
    }
    //扫码核销
    public function getInfoFromQr(Request $request){
        $data = $request->msg;



        try {
            $data = explode(',',base64_decode($data));
        }catch (\Exception $e){
            return $this->failed("无效二维码");
        }


        $order = Order::with(["goods:order_id,goods_name,goods_price,goods_id,num,total_money","user:id,name,nickname,mobile"])
            ->select(['id','user_id','money','type','check_status','order_status','pay_status','check_time','created_at'])->find($data[0]);
        if(!$order)
            return $this->failed("二维码不合法");

        if($order->pay_status==0){
            return $this->failed("订单未支付");
        }
        if($order->check_status==1){
            return $this->failed("订单已核销");
        }

        $order->check_status = 1;
        $order->order_status = 2;
        $order->check_time = date("Y-m-d H:i:s");
        $order->save();



        foreach ($order->goods as $k=>$v){
            $goods =  Good::with(["color:id,color","material:id,material"])
                ->where('id',$v['goods_id'])->select(['id','color_id','material_id','No',])->first();
            $order->goods[$k]->color = $goods->color->color;
            $order->goods[$k]->No = $goods->No;
            if($goods->material){
                $order->goods[$k]->str = $goods->color->color.'-'.$goods->material->material;
            }

        }




        return $this->success($order);
    }



    //订单核销
    public function ckeckQrCode(Request $request){

        $order_id = $request->order_id;



        $order = Order::find($order_id);

        if(!$order)
            return $this->failed("订单不存在");

        if($order->pay_status==0){
            return $this->failed("订单未支付");
        }
        if($order->check_status==1){
            return $this->failed("订单已核销");
        }


        $order->check_status = 1;
        $order->order_status = 2;
        $order->check_time = date("Y-m-d H:i:s");
        $order->save();

        return $this->success("核销成功");

    }


    //订单列表
    public function getAdminOrderList(Request $request){


       // $keywords = $request->check_status; //核销状态


        $where = function($query) use ($request){
            if($request->check_status || $request->check_status===0||$request->check_status==='0'){
                $query->where('check_status',$request->check_status);
            }

            if($request->start_time&&$request->end_time){
                $query->whereBetween('created_at',[$request->start_time,$request->end_time]);
            }

            if($request->keywords){
                $query->whereHas('user',function ($query) use ($request){
                    return $query->where('mobile', 'like', '%'.$request->keywords.'%')
                        ->orWhere('nickname', 'like', '%'.$request->keywords.'%');
                });
            }

            if($request->order_status || $request->order_status===0 || $request->order_status==='0'){
                $query->where('order_status',$request->order_status);
            }
        };

        $list = Order::with(['user:id,mobile,name,nickname'])->where($where)
            ->select(['id','user_id','check_status','order_status','type','created_at'])
            ->orderBy('id','desc')->paginate($request->pageSize?:15);

        return $this->success($list);
    }


    //修改订单价格
    public function ChangePrice(Request $request){

        $order_id = $request->order_id;
        $money = $request->money; //修改后价格
        $price_note = $request->price_note; //改价备注

        if(!$order_id || ! $money){
            return $this->failed('参数不全');
        }

        $order = Order::find($order_id);

        if($order->pay_status == 1)
            return $this->failed('订单已支付');

        $order->old_money = $order->money;
        $order->money = $money;
        $order->price_note = $price_note;

        $res = $order->save();

        if($res)
            return $this->success('操作成功');


        return $this->failed('操作失败');

    }

    public function removeEmojiChar($str)//去除字符串里的表情
    {
        $mbLen = mb_strlen($str);

        $strArr = [];
        for ($i = 0; $i < $mbLen; $i++) {
            $mbSubstr = mb_substr($str, $i, 1, 'utf-8');
            if (strlen($mbSubstr) >= 4) {
                continue;
            }
            $strArr[] = $mbSubstr;
        }

        return implode('', $strArr);

    }

    //打印订单标签
    public function PrintOrder(Request $request){

        $order_id = $request->order_id;

        $order = Order::with(["goods:order_id,goods_name,goods_id,goods_price,num,total_money","user:id,name,nickname,mobile"])
            ->select(['id','user_id','money','type','old_money','check_status','order_status','pay_status','pay_time','type','check_time','created_at'])->find($order_id);



        $user = User::find($order->user_id);
        $message = [];
        $message['print'][] = ['cont'=>'兰蚌优品','type'=>'title','size'=>35];

        $dev_id = DB::table('print_device')->where('type',2)->where('cate',$order->type)->where('status',1)->value('device_code');
        if($order->type == 1){
            $message['print'][] =  ['cont'=>'开蚌(客户联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
            //$dev_id = 'SW244700133';

        }elseif($order->type == 2){
            $message['print'][] =  ['cont'=>'配件(客户联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
            //$dev_id = 'SW244700137';
        }else{
            $message['print'][] =  ['cont'=>'成品(客户联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
            //$dev_id = 'SW244700137';
        }
        $message['print'][] = ['type'=>'div_line'];
        $message['print'][] = ['cont'=>'下单用户 ：'.$this->removeEmojiChar($user->nickname)];
        $message['print'][] = ['cont'=>'联系电话 ：'.substr_replace($user->mobile, '****', 3, 4)];
        $message['print'][] = ['cont'=>'下单时间 ：'.$order->pay_time];
        $message['print'][] = ['cont'=>'核销时间 ：'.$order->check_time];
        $message['print'][] = ['cont'=>'商品清单','type'=>'div_line'];
        foreach ($order->goods as $k=>$v){

            $goods =  Good::with(["color:id,color","material:id,material"])
                ->where('id',$v['goods_id'])->select(['id','color_id','material_id','No',])->first();

            $message['print'][] = ['cont'=>($k+1).'.'.$v['goods_name'],'type'=>'text'];
            $message['print'][] = ['cont'=>'  '.$goods->No,'type'=>'text'];
            $message['print'][] = ['both_sides'=>['  '.$goods->color->color.'-'.$goods->material->material,$v['goods_price'].'*'.$v['num'].'  ']];

        }
        $message['print'][] = ['type'=>'div_line'];

        $money = $order->old_money?:$order->money;

        $message['print'][] = ['both_sides'=>['总计','￥ '.$money],'size'=>12];

        $message['print'][] = ['cont'=>'优惠价'.'￥ '.$order->money,'type'=>'text','size'=>12,'align'=>'right'];
        $message['print'][] = ['cont'=>'https://mp.weixin.qq.com/a/~kdAM72icbwY0dJyxiOHGug~~','type'=>'qrcode','align'=>'center','size'=>6];
        $message['print'][] = ['cont'=>'浙中首家','type'=>'text','align'=>'center','bold'=>true,'size'=>18];
        $message['print'][] = ['cont'=>'珍珠开蚌体验基地','type'=>'text','align'=>'center','bold'=>true,'size'=>15];

        $message['print'][] = ['cont'=>''];
        $message['print'][] = ['type'=>'div_line'];
        $message['print'][] = ['cont'=>''];
        $message1 = $message;

        if($order->type == 1){
            $message1['print'][1] =  ['cont'=>'开蚌(存根联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
        }elseif($order->type == 2){
            $message1['print'][1] =  ['cont'=>'配件(存根联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
        }else{
            $message1['print'][1] =  ['cont'=>'成品(存根联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
        }

        $message1['print'] = array_slice($message1['print'], 0, -6);

        $message2 = [];

        $message2['print'] = array_merge($message['print'],$message1['print']);
        $print = new PrintController();



        $res = $print->printTicket($message2,$dev_id);

        if($res['code'] == 200){

            return $this->success($res);

        }else{

            return $this->failed($res['data']['message']);
        }



    }


    //打印商品标签
    public function PrintGoods(Request $request){

        $goods_id = $request->goods_id;
        $num = $request->num;

        $goods = Good::with(["color:id,color","material:id,material"])
            ->select(['id','color_id','specs','material_id','name','old_price','No','new_price','cate'])->find($goods_id);//获取商品列表


        //"SIZE":[40, 60],
        // "DIRECTION":0,
        // "DENSITY": 7,
        // "SOUND":3,
        //								"label":[
        //								{"type":"TEXT", "x":10, "y":20, "font":"2", "w":2 , "h":2, "r":0, "cont":"1234567889"},
        //								{"type":"QRCODE", "x":10, "y":60, "e":"M", "w":5 , "cont":"12345678"},
        //								{"type":"BC128", "x":10, "y":170, "h":20, "show":0, "r":0, "narrow":1, "wide":1,
        //								"cont":"1234567889"},
        //								{"type":"BAR", "x":10, "y":200, "w":200 , "h":2}

        $message = [];
        $message['SIZE'] = [30, 20];
        $message['label'][] = ['type'=>"TEXT",'x'=>0,'y'=>8,'font'=>'2',"w"=>'','h'=>'','cont'=>$goods->name];
        if($goods->cate < 3){
            $message['label'][] = ['type'=>"TEXT",'x'=>0,'y'=>33,'font'=>'',"w"=>1,'cont'=>$goods->specs];
            $message['label'][] = ['type'=>"TEXT",'x'=>0,'y'=>58,'font'=>'',"w"=>'','h'=>'','cont'=>$goods->material->material];
            $message['label'][] = ['type'=>"TEXT",'x'=>0,'y'=>81,'font'=>'',"w"=>'','h'=>'','cont'=>$goods->color->color];
        }

        $message['label'][] = ['type'=>"QRCODE",'x'=>140,'y'=>83,"w"=>3,'cont'=>$goods->No];
        $message['label'][] = ['type'=>"TEXT",'x'=>0,'y'=>105,'cont'=>$goods->No];
        $message['label'][] = ['type'=>"TEXT",'x'=>0,'y'=>130,'cont'=>"￥".$goods->new_price];

//"r":0, "narrow":1, "wide":1,

        $dev_id = DB::table('print_device')->where('type',1)->where('cate',$goods->cate)->where('status',1)->value('device_code');
        $print = new PrintController();

        $res = $print->printTicket($message,$dev_id,2,$num);

        return $this->success($res);

    }

    public function getAdminGoodList(Request $request){

        $user = Auth::guard('api')->user();
        $type = $request->type; //1开蚌  2饰品
        $cate = $request->cate; //饰品分类
        $keywords = $request->keywords; //搜索

        $where = function($query) use ($request){

            if($request->type){
                $query->where('cate',$request->type);
            }
            if($request->cate){ //饰品分类
                $query->where('type_id',$request->cate);
            }

            if($request->keywords){
                $query->where(function ($query) use ($request){
                    $query->Where('name', 'like', '%'.$request->keywords.'%')->orWhere('No', 'like', '%'.$request->keywords.'%');
                });

            }

            //$query->where('status',1);
        };


        $goods_list = Good::with(["color:id,color","material:id,material"])
            ->where($where)
//            ->when($keywords,function($query) use ($keywords){
//                $query->where(function ($query) use ($keywords){
//                    return $query->whereHas('user', function ($query) use ($keywords) {
//                        return $query->where('mobile', 'like', '%'.$keywords.'%');
//                    })->orWhereHas('activity',function ($query) use ($keywords){
//                        return $query->Where('title', 'like', '%'.$keywords.'%');
//                    });
//                });
//
//            })
            ->select(['id','color_id','material_id','name','img','old_price','No','new_price','stock'])->paginate($request->pageSize?:20);//获取商品列表

        foreach ($goods_list as $k=>$v){

            $goods_list[$k]->thumb_img =$v->img[0];
            if($v->material){
                $goods_list[$k]->str = $v->color->color."-". $v->material->material;
            }else{
                $goods_list[$k]->str = "";
            }


        }


        return $this->success($goods_list);

    }

    public function changeStock(Request $request){
        $goods_id = $request->goods_id;
        $stock = $request->stock;

        $goods = Good::find($goods_id);

        if(!$goods)
            return $this->failed('商品信息不存在');

        if ($stock < 0)
            return $this->failed('库存必须大于0');

        $goods->stock = $stock;

        $goods->save();

        return $this->success('修改成功');
    }

    //修改商品价格
    public function changeGoodsPrice(Request $request){
        $goods_id = $request->goods_id;
        $old_price = $request->old_price;
        $new_price = $request->new_price;

        $goods = Good::find($goods_id);

        if(!$goods)
            return $this->failed('商品信息不存在');

        if ($old_price < $new_price)
            return $this->failed('现价不可大于原价');

        $goods->new_price = $new_price;
        $goods->old_price = $old_price;

        $goods->save();

        return $this->success('修改成功');
    }


    //获取商品分类
    public function getCate(Request $request){

        $type = $request->type;

        return $this->success( DB::table('type')->where('type',$type)->pluck('name','id'));
    }

    //获取商品颜色
    public function getColor(Request $request){
        return $this->success( DB::table('color')->pluck('color','id'));
    }

    //获取商品材质
    public function getMaterial(Request $request){
        return $this->success( DB::table('material')->pluck('material','id'));
    }

    //获取商品供应商
    public function getSupplier(Request $request){

        return $this->success( DB::table('supplier')->pluck('name','id'));
    }

    //新增商品
    public function addGoods(Request $request){

        $cate = $request->cate;

        if($cate ==3){
            $validator = Validator::make($request->all(), [
                'name' => 'required|max:100',
                //'type_id' => 'required',
                'supplier_id' => 'required',
                //'color_id' => 'required',
                //'specs' => 'required',
                //'material_id' => 'required',
                //'No' => 'required',
                //'model' => 'required',
                'img' => 'required',
                'cate' => 'required|in:1,2,3',
                'old_price' => 'required',
                'new_price' => 'required',
                'cost_price' => 'required',
                'stock' => 'required|numeric|gt:0',
            ], [
                'required' => '缺少必填参数',
                'stock.gt' => '库存必须大于0',
                'cate' => '大类不合法',
            ]);

        }else{
            $validator = Validator::make($request->all(), [
                'name' => 'required|max:100',
                'type_id' => 'required',
                'supplier_id' => 'required',
                'color_id' => 'required',
                'specs' => 'required',
                'material_id' => 'required',
                //'No' => 'required',
                'model' => 'required',
                'img' => 'required',
                'cate' => 'required|in:1,2,3',
                'old_price' => 'required',
                'new_price' => 'required',
                'cost_price' => 'required',
                'stock' => 'required|numeric|gt:0',
            ], [
                'required' => '缺少必填参数',
                'stock.gt' => '库存必须大于0',
                'cate' => '大类不合法',
            ]);
        }



        if ($validator->fails())
        {
            return $this->failed($validator->errors()->first());
        }

        $data = $request->toArray();

        if(!$request->No){

            $supplier = Supplier::find($data['supplier_id']);

            $data['No'] = $supplier->number.'-'.rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);

        }


        $data['created_at'] = date("Y-m-d H:i:s");
        $data['updated_at'] = date("Y-m-d H:i:s");

        $goods = DB::table('goods')->insert($data);

        if($goods)

            return $this->success('创建成功');


        return $this->failed('创建失败');

    }


    //商品详情
    public function getGoodsInfo(Request $request){
        $goods_id = $request->goods_id;

        if(!$goods_id)
            return $this->failed('缺少必要参数');

        return $this->success(Good::find($goods_id));
    }

    //编辑商品
    public function editGoods(Request $request){

        $validator = Validator::make($request->all(), [
            'name' => 'required|max:100',
            'goods_id' => 'required|exists:goods,id',
            'type_id' => 'required',
            'supplier_id' => 'required',
            'color_id' => 'required',
            'specs' => 'required',
            'material_id' => 'required',
            //'No' => 'required',
            'model' => 'required',
            'img' => 'required',
            'cate' => 'required|in:1,2,3',
            'old_price' => 'required',
            'new_price' => 'required',
            'cost_price' => 'required',
            'stock' => 'required|numeric|gt:0',
        ], [
            'required' => '缺少必填参数',
            'stock.gt' => '库存必须大于0',
            'cate.in' => '大类不合法',
            'goods_id.exists' => '商品不存在',
        ]);

        if ($validator->fails())
        {
            return $this->failed($validator->errors()->first());
        }

        $data = $request->toArray();

        if(!$request->No){

            $supplier = Supplier::find($data['supplier_id']);

            $data['No'] = $supplier->number.rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);

        }



        $data['updated_at'] = date("Y-m-d H:i:s");

        unset($data['goods_id']);
        $goods = DB::table('goods')->where('id',$request->goods_id)->update($data);

        if($goods)

            return $this->success('编辑成功');


        return $this->failed('编辑失败');

    }



}
